<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>基本资料</span>
        <div class="edit-button-container">
          <el-button type="primary" @click="toggleEdit" v-if="!isEditing">修改</el-button>
          <el-button type="primary" @click="updateUser" v-if="isEditing">提交修改</el-button>
          <el-button type="primary" @click="endEdit" v-if="isEditing">取消</el-button>
        </div>
      </div>
    </template>
    <!--    客户信息-->
    <div class="user-info-container">
      <el-image
          :src="userInfo.userPic || defaultImage "
          fit="cover"
          class="user-avatar">
        <template #error>
          <div class="image-error">封面加载失败</div>
        </template>
      </el-image>
      <el-row v-if="!isEditing">
        <el-col :span="12">
          <div class="info-item">
            <span class="label">登录名称：</span>
            <span>{{ userInfo.username }}</span>
          </div>
          <div class="info-item">
            <span class="label">用户昵称：</span>
            <span>{{ userInfo.nickname }}</span>
          </div>
          <div class="info-item">
            <span class="label">用户邮箱：</span>
            <span>{{ userInfo.email }}</span>
          </div>
          <div class="info-item">
            <span class="label">用户电话：</span>
            <span>{{ userInfo.phone }}</span>
          </div>
        </el-col>
      </el-row>
      <el-row v-else>
        <el-col :span="12">
          <el-form :model="userInfo" :rules="rules" label-width="100px" size="large">
            <el-form-item label="登录名称">
              <el-input v-model="userInfo.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="用户昵称" prop="nickname">
              <el-input v-model="userInfo.nickname"></el-input>
            </el-form-item>
            <el-form-item label="用户邮箱" prop="email">
              <el-input v-model="userInfo.email"></el-input>
            </el-form-item>
            <el-form-item label="用户电话" prop="email">
              <el-input v-model="userInfo.phone"></el-input>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>

    <!--    委托房源信息-->
    <div>
      <h2>委托房源</h2> <!-- 添加的标题 -->
      <el-row>
        <!-- 表格内容 -->
        <el-table :data="houseListData" style="width: 100% ;margin-top: 30px;" v-loading="loading">
          <el-table-column label="序号" width="60" type="index" />
          <el-table-column label="封面" prop="cover" width="120">
            <template #default="{ row }">
              <el-image
                  style="width: 80px; height: 80px; border-radius: 4px;"
                  :src="row.cover"
                  v-if="row.cover"
                  fit="cover"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <span v-else>无封面</span>
            </template>
          </el-table-column>
          <el-table-column label="面积" prop="area">
            <template #default="{ row }">
              {{ row.area }}㎡
            </template>
          </el-table-column>
          <el-table-column label="价格" prop="price">
            <template #default="{ row }">
              ¥{{ row.price.toLocaleString() }}
            </template>
          </el-table-column>
          <el-table-column label="地址" prop="address" />
          <el-table-column label="状态">
            <template #default="{ row }">
              <el-tag
                  :type="{
              0: 'warning',
              1:'success',
              2: 'info',
              3: ''
            }[row.status]"
              >
                {{
                  {
                    0: '待审核',
                    1: '已发布',
                    2: '已下架',
                    3: '已成交'
                  }[row.status]
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="类型">
            <template #default="{ row }">
              <el-tag
                  :type="{
              0: 'warning',
              1:'success'
            }[row.type]"
              >
                {{
                  {
                    0: '售房',
                    1: '租房'
                  }[row.type]
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="发布日期" prop="publishTime" />
          <el-table-column label="房东姓名" prop="landlordName" />
          <el-table-column label="操作" width="180">
            <template #default="{ row }">
              <el-button
                  :icon="Document"
                  circle
                  plain
                  type="info"
                  @click="handleEdit(row)"
              />
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无房源数据" />
          </template>

        </el-table>

        <!-- 分页条 -->
        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
                       layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
                       @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />




      </el-row>
    </div>

    <!--    预约信息-->
    <div>
      <h2 >已完成预约看房</h2> <!-- 添加的标题 -->
      <el-row>
        <!-- 表格内容 -->
        <el-table :data="ListData" style="width: 100% ;margin-top: 30px;" v-loading="loading">
          <el-table-column label="序号" width="70" type="index" />
          <el-table-column label="头像" prop="userCusPic" width="100px">
            <template #default="{ row }">
              <el-image
                  style="width: 60px; height: 60px; border-radius: 50%;"
                  :src="row.userCusPic"
                  v-if="row.userCusPic"
                  fit="cover"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <span v-else>无头像</span>
            </template>
          </el-table-column>

          <el-table-column label="昵称" prop="customerName" />
          <el-table-column label="客户电话" prop="cusTel" />
          <el-table-column label="预约时间" prop="appointmentTime" />
          <el-table-column label="房源地址" prop="address" />
          <el-table-column label="小区名称" prop="communityName" />
          <el-table-column label="房源类型">
            <template #default="{ row }">
              <el-tag
                  :type="{
              0: 'info',
              1:'success'
            }[row.type]"
              >
                {{
                  {
                    "0": '卖房',
                    "1": '租房',
                  }[row.type]
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="预约状态">
            <template #default="{ row }">
              <el-tag
                  :type="{
              0: 'warning',
              1:'success',
              2: 'info',
              3: ''
            }[row.status]"
              >
                {{
                  {
                    0: '待确认',
                    1: '已确认',
                    2: '已取消',
                    3: '已完成'
                  }[row.status]
                }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="240">
            <template #default="{ row }">
              <el-button
                  type="success"
                  :icon="Check"
                  circle
                  plain
                  @click="editYuyue(row)"
              ></el-button>
              <el-button
                  type="danger"
                  :icon="Close"
                  circle
                  plain
                  @click="handleCancel(row)"
              ></el-button>
            </template>
          </el-table-column>


          <template #empty>
            <el-empty description="暂无用户数据" />
          </template>
        </el-table>

        <!-- 分页条 -->
        <el-pagination
            v-model:current-page="pageNum2"
            v-model:page-size="pageSize2"
            :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next"
            background
            :total="total2"
            @size-change="onSizeChange2"
            @current-change="onCurrentChange2"
            style="margin-top: 20px; justify-content: flex-end"
        />


      </el-row>
      <!-- 创建合同 -->
      <el-dialog v-model="yuyueVisible" title="创建合同" width="60%">
        <el-form :model="contract" label-width="120px" style="padding: 20px;">
          <el-form-item label="生效日期">
            <el-date-picker
                v-model="contract.createTime"
                type="date"
                placeholder="选择生效日期"
                :size="size"
            />
          </el-form-item>
          <el-form-item v-if="housetype" label="输入合同月份">
            <el-input v-model="contract.yuefen" :size="size"/>
          </el-form-item>
          <el-form-item label="中介费金额">
            <el-input v-model="contract.intAmount" :size="size" />
          </el-form-item>
          <el-form-item label="上传合同">
            <el-upload
                class="contract-uploader"
                :auto-upload="true"
                action="/api/upload"
                :headers="{ 'Authorization': tokenStore.token }"
                :show-file-list="false"
                :before-upload="beforeContractUpload"
                :on-success="handleUploadSuccess"
                accept=".pdf,.doc,.docx">
              <el-input
                  v-model="contract.content"
                  placeholder="点击上传合同文件"
                  readonly>
                <template #suffix>
                  <el-icon class="upload-icon"><Upload /></el-icon>
                </template>
              </el-input>
            </el-upload>
          </el-form-item>



        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <!-- 取消按钮 -->
        <el-button @click="yuyueVisible = false">取消</el-button>
        <!-- 确认按钮 -->
        <el-button type="primary" @click="yuyueeditOk()"> 确认 </el-button>
      </span>
        </template>
      </el-dialog>



    </div>

    <!--   合同信息-->
    <div>
      <h2 >合同信息</h2> <!-- 添加的标题 -->
      <el-row>
        <!-- 表格内容 -->
        <el-table :data="contractListData" style="width: 100% ;margin-top: 30px;" v-loading="loading">
          <el-table-column label="序号" width="70" type="index" />
          <el-table-column label="客户昵称" prop="username" />
          <el-table-column label="房东昵称" prop="landlordname" />
          <el-table-column label="签约时间" prop="createTime" />
          <el-table-column label="到期时间" prop="endTime" />
          <el-table-column label="服务费" prop="intAmount" />
          <el-table-column label="房源费用" prop="houseAmount" />
          <el-table-column label="房源类型">
            <template #default="{ row }">
              <el-tag
                  :type="{
              0: 'info',
              1:'success'
            }[row.type]"
              >
                {{
                  {
                    "0": '卖房',
                    "1": '租房',
                  }[row.type]
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="预约状态">
            <template #default="{ row }">
              <el-tag
                  :type="{
              0: 'warning',
              1:'success',
              2: 'info'
            }[row.status]"
              >
                {{
                  {
                    0: '未支付',
                    1: '已生效',
                    2: '已失效'
                  }[row.status]
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="合同信息" prop="content">
            <template #default="{ row }">
              <el-button
                  v-if="row.content"
                  type="primary"
                  link
                  @click="downloadContract(row.content)"
              >
                下载合同
              </el-button>
              <span v-else>无合同文件</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240">
            <template #default="{ row }">
              <el-button
                  type="success"
                  :icon="Check"
                  circle
                  plain
                  @click="edithetong(row)"
              ></el-button>
              <el-button
                  type="danger"
                  :icon="Close"
                  circle
                  plain
                  @click="handleCancelhetong(row)"
              ></el-button>
            </template>
          </el-table-column>


          <template #empty>
            <el-empty description="暂无用户数据" />
          </template>
        </el-table>

        <!-- 分页条 -->
        <el-pagination
            v-model:current-page="pageNum3"
            v-model:page-size="pageSize3"
            :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next"
            background
            :total="total3"
            @size-change="onSizeChange3"
            @current-change="onCurrentChange3"
            style="margin-top: 20px; justify-content: flex-end"
        />

      </el-row>

    </div>




  </el-card>
</template>

<script setup>
import { ref } from 'vue'
import { updateUserInfo } from "@/api/user.js";
import {ElMessage, ElMessageBox} from "element-plus";
import defaultImage from "@/assets/imgmoren.png";
import {Check, Close, Document, Plus} from "@element-plus/icons-vue";
import {housesListService} from "@/api/housesList.js";
import {useRouter} from "vue-router";
import {deleteAppointmentsService, getAppointmentsPageList} from "@/api/appointments.js";
import { useUserInfoStore } from "@/stores/userinfo.js";
const userInfoStore = useUserInfoStore()
const userinfoId = userInfoStore.info.id;
const userInfo = ref({
  ...userInfoStore.info
});
// 房源列表数据模型
const houseListData = ref([])
const ListData = ref([])
const contractListData = ref([])
const contract = ref({
  createTime:'',
  yuefen:'',
  landlordId:'',
  userId:'',
  houseId:'',
  intermediaryId:'',
  intAmount:'',
  houseAmount:'',
  content:'',
})
const handleUploadSuccess = (result) => {
  contract.value.content = result.res;
}
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
// 文件验证
const beforeContractUpload = (file) => {
  const allowedTypes = ['application/pdf', 'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
  const extension = file.name.split('.').pop().toLowerCase()

  if (!allowedTypes.includes(file.type) || !['pdf','doc','docx'].includes(extension)) {
    ElMessage.error('仅支持PDF/DOC/DOCX格式')
    return false
  }

  // 添加大小限制（示例50MB）
  const isLt50M = file.size / 1024 / 1024 < 50
  if (!isLt50M) {
    ElMessage.error('文件大小不能超过50MB')
    return false
  }
  return true
}
const isEditing = ref(false); // 控制是否处于编辑状态
// 分页条数据模型
const pageNum = ref(1) // 当前页
const total = ref(0) // 总条数
const pageSize = ref(15) // 每页条数
// 分页条数据模型
const pageNum2 = ref(1) // 当前页
const total2 = ref(0) // 总条数
const pageSize2 = ref(15) // 每页条数
// 分页条数据模型
const pageNum3 = ref(1) // 当前页
const total3 = ref(0) // 总条数
const pageSize3 = ref(15) // 每页条数
const size = ref('default');
const yuyueVisible = ref(false)
const housetype = ref(false)
import {useTokenStore} from "@/stores/token.js";
import {addContractService, deleteContractService, getContractPageList, updateContract} from "@/api/contract.js";
const tokenStore = useTokenStore();
const rules = {
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    {
      pattern: /^\S{2,10}$/,
      message: '昵称必须是2-10位的非空字符串',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入用户邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ]
};
const yuyueeditOk = async () => {
  let resul = await addContractService(contract.value);
  ElMessage.success('修改成功');

  console.log('提交合同信息:', contract.value);
  yuyueVisible.value = false;
  ListArray();
  contractListArray();
};
const updateUser = async () => {
  let resul = await updateUserInfo(userInfo.value);
  ElMessage.success('修改成功');
  userInfoStore.setInfo(userInfo.value);
  isEditing.value = false; // 修改成功后回到非编辑状态
};

// 查看操作
const router = useRouter()
const handleEdit = (row) => {
  if (row.type==="0"){
    let IntType= "3";
    router.push({
      name: 'housesItemDetailIntBuy',
      params: { id: row.id , IntType:IntType},
    })
  }else if (row.type==="1"){
    let IntType= "3";
    router.push({
      name: 'housesItemDetailIntRes',
      params: { id: row.id , IntType:IntType},
    })
  }
}
const toggleEdit = () => {
  isEditing.value = true; // 进入编辑状态
};
const endEdit = () => {
  isEditing.value = false; // 退出编辑状态
};
// 搜索条件数据模型
const searchForm = ref({
  intermediaryId: userinfoId,
  status:'1'
})
const searchFormhetong = ref({intermediaryId:userinfoId,type:'' })
const searchFormYuyue = ref({ appointmentTime: '',type:'',status:'1'})
// 当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  // 重新获取数据
  housesList()
}
// 当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num
  // 重新获取数据
  housesList()
}
// 当每页条数发生了变化，调用此函数
const onSizeChange2 = (size) => {
  pageSize2.value = size
  // 重新获取数据
  ListArray()
}
// 当前页码发生变化，调用此函数
const onCurrentChange2 = (num) => {
  pageNum2.value = num
  // 重新获取数据
  ListArray()
}
// 当每页条数发生了变化，调用此函数
const onSizeChange3 = (size) => {
  pageSize3.value = size
  // 重新获取数据
  contractListArray()
}
// 当前页码发生变化，调用此函数
const onCurrentChange3 = (num) => {
  pageNum3.value = num
  // 重新获取数据
  contractListArray()
}
const loading = ref(false);
// 获取房源列表数据
// 获取房源列表
const housesList = async () => {
  try {
    loading.value = true
    const result = await housesListService({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...searchForm.value
    })
    if (result && result.res) {
      houseListData.value = result.res.items
      total.value = result.res.total
    } else {
      console.error('接口返回数据格式不正确，缺少 data 属性')
      ElMessage.error('加载房源列表失败，接口返回数据格式不正确')
    }
  } catch (error) {
    console.error('数据获取失败:', error)
    ElMessage.error('加载房源列表失败')
  } finally {
    loading.value = false
  }
}

// 获取列表数据
const ListArray = async () => {
  loading.value = true
  const params = {
    ...searchFormYuyue.value,
  };
  try {
    const result = await getAppointmentsPageList(
        pageNum2.value,
        pageSize2.value,
        params
    )
    ListData.value = result.res.items
    total2.value = result.res.total // 确保接口返回total字段
  } finally {
    loading.value = false
  }
}
const contractListArray = async () => {
  loading.value = true
  const params = {
    ...searchFormhetong.value,
  };
  try {
    const result = await getContractPageList(
        pageNum3.value,
        pageSize3.value,
        params
    )
    contractListData.value = result.res.items
    total3.value = result.res.total // 确保接口返回total字段
  } finally {
    loading.value = false
  }
}

const handleCancel = (row) => {
  ElMessageBox.confirm('此操作将取消预约申请, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteAppointmentsService(row.id)
    ElMessage.success('预约已取消')
    ListArray()

  }).catch(() => {
    ElMessage.info('取消删除')
  })
}
const editYuyue = (row) => {
  contract.value = {
    createTime:'',
    endTime:'',
    landlordId: '',
    houseId: row.houseId,
    userId: row.customerId,
    intermediaryId:userinfoId,
    intAmount:'',
    houseAmount:'',
    content:''
  }
  if (row.type==="1"){
    housetype.value = true;
  }else {
    housetype.value = false;
  }

  yuyueVisible.value = true;
}



const downloadContract = (url) => {
  if (!url) {
    ElMessage.error('合同文件不存在');
    return;
  }

  // 如果URL是完整路径直接下载
  if (url.startsWith('http')) {
    window.open(url);
    return;
  }

  // 如果URL是相对路径，拼接基础URL（根据你的实际接口调整）
  const fullUrl = `http://your-api-domain.com${url}`;

  // 使用axios下载（需要处理跨域和认证时）
  axios({
    url: fullUrl,
    method: 'GET',
    responseType: 'blob',
    headers: {
      'Authorization': tokenStore.token // 如果需要认证
    }
  }).then(response => {
    const blob = new Blob([response.data]);
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = url.split('/').pop() || 'contract';
    link.click();
    URL.revokeObjectURL(link.href);
  }).catch(error => {
    ElMessage.error('文件下载失败');
    console.error('下载失败:', error);
  });
}

const handleCancelhetong = (row) => {
  ElMessageBox.confirm('此操作删除合同, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteContractService(row.id)
    ElMessage.success('删除成功')
    contractListArray()
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}
const edithetong = (row) => {
  ElMessageBox.confirm('确定收款后合同生效, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await updateContract({
      id:row.id
    })

    contractListArray();
    ElMessage.success('合同已生效')
    ListArray()
  }).catch(() => {
    // ElMessage.info('取消操作')
  })
}

housesList();
ListArray();
contractListArray();

</script>

<style scoped>
.page-container {
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.header {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.edit-button-container {
  display: flex;
  align-items: center;
}

.user-info-container {
  text-align: center;
}

.user-avatar {
  width: 150px;
  height: 150px;
  margin: 0 auto 20px;
  border-radius: 50%;
  overflow: hidden;
  border: 4px solid #fff;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.2);
}

.info-item {
  margin-bottom: 10px;
  text-align: left;
  font-size: 16px;
  color: #555;
}

.label {
  font-weight: bold;
  margin-right: 10px;
  color: #333;
}
.dialog-footer {
  text-align: right;
  padding: 10px 20px;
}
/* 统一输入框样式 */
.contract-uploader .el-input__inner {
  cursor: pointer;
  background-color: #f5f7fa;
  &:hover {
    border-color: #409eff;
  }
}

/* 上传图标美化 */
.upload-icon {
  color: #409eff;
  font-size: 18px;
  margin-right: 8px;
}

</style>
